import React, { useEffect, useRef, useState } from 'react'
import { loadScript } from '@/utils/loadScript'
import { CDN_ECHARTS } from '@/lib/utils'
import { BattleValueExt2 } from '@/types/sun'

interface SmoothLineChartProps {
  data: BattleValueExt2[]
  // 默认值 Damage
  damage?: string
  receive?: string
  tag?: string
  title: string
  height?: string
}

const SmoothData: React.FC<SmoothLineChartProps> = ({
  data,
  title,
  damage = 'Damage',
  receive = 'Receive',
  tag = 'Count',
  height = '500px'
}) => {
  const chartRef = useRef<HTMLDivElement>(null)
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const chartInstance = useRef<any>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let isMounted = true
    setLoading(true)

    // 若无数据，直接结束 loading
    if (!data || !Array.isArray(data) || data.length === 0) {
      setLoading(false)
      if (chartInstance.current) {
        chartInstance.current.dispose()
        chartInstance.current = null
      }
      return
    }

    function renderChart() {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      if (!(window as any).echarts || !chartRef.current) return
      // 销毁旧实例，防止重复初始化
      if (chartInstance.current) {
        chartInstance.current.dispose()
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      chartInstance.current = (window as any).echarts.init(
        chartRef.current,
        undefined,
        {
          renderer: 'canvas'
        }
      )
      const chart = chartInstance.current

      const xAxisData = data.map((item) => item.name)
      const yAxisData = [
        {
          name: damage,
          type: 'line',
          data: data.map((item) => item.damage),
          smooth: true
        },
        {
          name: receive,
          type: 'line',
          data: data.map((item) => item.receive),
          smooth: true
        }
      ]

      if (tag) {
        yAxisData.push({
          name: tag,
          type: 'line',
          data: data.map((item) => item.count),
          smooth: true
        })
      }

      const option = {
        title: {
          text: title
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params: { seriesName: string; value: number }[]) => {
            return params
              .map(
                (param) =>
                  `${param.seriesName}: ${
                    param.value?.toLocaleString?.() ?? param.value
                  }`
              )
              .join('<br/>')
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: yAxisData
      }
      chart.setOption(option)
      chart.resize()
      setLoading(false)
    }

    // 增加超时时间和重试次数
    function waitForEcharts(retry = 60) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      if ((window as any).echarts && chartRef.current && isMounted) {
        renderChart()
      } else if (retry > 0) {
        setTimeout(() => waitForEcharts(retry - 1), 300)
      } else {
        setLoading(false)
        // 提示用户加载失败
        if (chartRef.current) {
          chartRef.current.innerHTML =
            '<div style="color:red;text-align:center;padding:2em;">ECharts 加载超时，请检查网络或稍后重试。</div>'
        }
      }
    }

    loadScript(CDN_ECHARTS)
      .then(() => {
        waitForEcharts()
      })
      .catch((e) => {
        setLoading(false)
        // eslint-disable-next-line no-console
        console.error('ECharts 加载失败', e)
      })

    // 监听窗口大小变化，自动 resize
    function handleResize() {
      if (chartInstance.current) {
        chartInstance.current.resize()
      }
    }
    window.addEventListener('resize', handleResize)

    return () => {
      isMounted = false
      window.removeEventListener('resize', handleResize)
      if (chartInstance.current) {
        try {
          chartInstance.current.dispose()
        } catch (e) {
          // ignore dispose error
        }
        chartInstance.current = null
      }
    }
    // 只依赖 data、title，减少不必要的重渲染
  }, [damage, data, receive, tag, title, height])

  return (
    <div style={{ position: 'relative', minHeight: height, width: '100%' }}>
      {loading && (
        <div
          style={{
            position: 'absolute',
            left: 0,
            top: 0,
            width: '100%',
            height: '100%',
            zIndex: 1,
            background: 'rgba(255,255,255,0.6)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          加载中...
        </div>
      )}
      <div
        ref={chartRef}
        style={{ minHeight: height, width: '100%', background: '#fff' }}
      />
    </div>
  )
}

export default SmoothData
